const { getAddAndRemoveIdList } = require('../../../shared/repository/helper')
const SequelizeRepository = require('../../../shared/repository/SequelizeRepository')
const R = require('ramda')
class RoleRepository extends SequelizeRepository {
  constructor({ database, roleCoverter }) {
    super({
      coverter: roleCoverter,
      model: database.models.Role,
    })
    this.models = database.models
  }

  toMenu(id) {
    const { Menu } = this.models
    const menu = new Menu()
    menu.id = id
    return menu
  }
  toMenuList(menuIdList = []) {
    return R.map(this.toMenu.bind(this), menuIdList)
  }
  async findByCode(code) {
    return this.findOne({ where: { code } })
  }
  async updateAuthorization(
    entity,
    { menu: menuIdList },
    { transaction, currentUser }
  ) {
    const { id, name, description } = this.coverter.toDatabase(entity)
    const role = await this.model.findByPk(entity.id, {
      include: ['menuList'],
    })
    const { deleteIds, addIds } = getAddAndRemoveIdList(
      R.map(R.prop('id'), role.menuList),
      menuIdList
    )
    await role.removeMenuList(this.toMenuList(deleteIds), { transaction })
    await role.addMenuList(this.toMenuList(addIds), { transaction })
    await role.update(
      {
        name,
        description,
        updatedBy: this.getUsername(currentUser),
      },
      { where: { id }, transaction }
    )
  }
}

module.exports = RoleRepository
